package com.linglan.common.config;

import org.springframework.boot.validation.MessageInterpolatorFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import javax.validation.Validator;

@Configuration
public class I18nValidateWebConfig {
    private static MessageSource messageSource;

    public I18nValidateWebConfig(MessageSource messageSource) {
        I18nValidateWebConfig.messageSource = messageSource;
    }

    @Bean
    public Validator validator() {
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory();
        factoryBean.setMessageInterpolator(interpolatorFactory.getObject());
        //配置为快速失败模式
        factoryBean.getValidationPropertyMap().put("hibernate.validator.fail_fast", "true");
        factoryBean.setValidationMessageSource(messageSource);
        return factoryBean;
    }
}
